package com.wei.tang.ui.course;

import java.io.File;

import com.wei.tang.R;
import com.wei.tang.base.BaseActivity;
import com.wei.tang.util.Tlog;
import com.wei.tang.util.Util;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import butterknife.InjectView;
import butterknife.OnClick;

public class CourseAcitivity extends BaseActivity {

	private CourseAcitivity mySelf = this;

	@InjectView(R.id.sv_video)
	SurfaceView sv_video;

	@InjectView(R.id.sb_progress)
	SeekBar sb_progress;

	@InjectView(R.id.tv_describle)
	TextView tv_describle;

	private String svPath = "/sdcard/2.mp4";
	private String svImage = "classtitle0";
	private String tvDescrible = "大头儿子小头爸爸，爸爸的头小手儿大，儿子的头大手儿小，大手牵小手走路不怕滑，走呀走呀走呀走呀将来儿子长大了！";
	private MediaPlayer mediaPlayer;
	private int currentPosition = 0;
	private boolean isPlaying = false;

	@Override
	public int getLayoutId() {
		return R.layout.course_activity;
	}

	@Override
	public void initData() {

		if (getIntent().hasExtra("path")) {
			svPath = getIntent().getStringExtra("path");
		}

		if (getIntent().hasExtra("describle")) {
			tvDescrible = getIntent().getStringExtra("describle");
		}

		if (getIntent().hasExtra("image")) {
			svImage = getIntent().getStringExtra("image");
		}

		tv_describle.setText(tvDescrible);

	}

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	public void initView() {
		sv_video.getHolder().addCallback(new Callback() {
			// SurfaceHolder被修改的时候回调
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				Tlog.i("SurfaceHolder 被销毁");
				// 销毁SurfaceHolder的时候记录当前的播放位置并停止播放
				if (mediaPlayer != null && mediaPlayer.isPlaying()) {
					currentPosition = mediaPlayer.getCurrentPosition();
					mediaPlayer.stop();
				}
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				Tlog.i("SurfaceHolder 被创建");
				Canvas canvas = holder.lockCanvas();
				Resources res = mySelf.getResources();
				Bitmap black = BitmapFactory.decodeResource(res, Util.getResId(svImage, R.drawable.class));
				canvas.drawBitmap(black, 0, 0, null);
				// 绘制完成，释放画布，提交修改
				holder.unlockCanvasAndPost(canvas);
				// 重新锁两次，避免下次lockCanvas遮挡
				holder.lockCanvas(new Rect(0, 0, 0, 0));
				holder.unlockCanvasAndPost(canvas);
				holder.lockCanvas(new Rect(0, 0, 0, 0));
				holder.unlockCanvasAndPost(canvas);

				if (currentPosition > 0) {
					// 创建SurfaceHolder的时候，如果存在上次播放的位置，则按照上次播放位置进行播放
					play(currentPosition);
					currentPosition = 0;
				}
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				Tlog.i("SurfaceHolder 大小被改变");
			}

		});

		sb_progress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// 当进度条停止修改的时候触发
				// 取得当前进度条的刻度
				int progress = seekBar.getProgress();
				if (mediaPlayer != null && mediaPlayer.isPlaying()) {
					// 设置当前播放的位置
					mediaPlayer.seekTo(progress);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

			}
		});

		// play(currentPosition);
	}

	@Override
	@OnClick({ R.id.sv_video })
	public void onClick(View v) {
		Intent intent = null;
		int id = v.getId();
		switch (id) {
		case R.id.sv_video:
			if (isPlaying) {
				pause();
			} else {
				play(currentPosition);
			}
			break;
		}
	}

	/**
	 * 开始播放
	 * 
	 * @param msec
	 *            播放初始位置
	 */
	protected void play(final int msec) {
		// 获取视频文件地址
		File file = new File(svPath);
		if (!file.exists()) {
			Toast.makeText(this, "视频文件路径错误", 0).show();
			return;
		}
		try {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 设置播放的视频源
			mediaPlayer.setDataSource(file.getAbsolutePath());
			// 设置显示视频的SurfaceHolder
			mediaPlayer.setDisplay(sv_video.getHolder());
			Tlog.i("开始装载");
			mediaPlayer.prepareAsync();
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					Tlog.i("装载完成");
					mediaPlayer.start();
					// 按照初始位置播放
					mediaPlayer.seekTo(msec);
					// 设置进度条的最大进度为视频流的最大播放时长
					sb_progress.setMax(mediaPlayer.getDuration());
					// 开始线程，更新进度条的刻度
					new Thread() {
						@Override
						public void run() {
							try {
								isPlaying = true;
								while (isPlaying) {
									int current = mediaPlayer.getCurrentPosition();
									sb_progress.setProgress(current);

									sleep(500);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}.start();
				}
			});
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					// 在播放完毕被回调
					// isPlaying = false;
				}
			});

			mediaPlayer.setOnErrorListener(new OnErrorListener() {

				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					// 发生错误重新播放
					play(0);
					isPlaying = true;
					return false;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 暂停或继续
	 */
	protected void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		} else {
			mediaPlayer.start();
		}
	}

	/**
	 * 停止播放
	 */
	protected void stop() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.stop();
			mediaPlayer = null;
			isPlaying = false;
		}
	}

}
